#include "login.h"
#define MAXLEN 16
void getPassword(char *buffer, size_t maxLen) {
    struct termios oldt, newt;
    int i = 0;
    char ch;

    // 获取当前终端设置
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;

    // 关闭回显功能
    newt.c_lflag &= ~(ECHO);

    // 设置新终端属性
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    printf("请输入密码:");

    while (i < maxLen - 1) {
        ch = getchar();
        if (ch == '\n') break;

        buffer[i++] = ch;
        printf("*"); // 显示星号
        fflush(stdout);
    }
    buffer[i] = '\0';

    // 恢复终端设置
    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    printf("\n");
}

int login(int socketFd) {
    printf("请输入用户名:");
    char name[MAXLEN];
    scanf("%s",name);
    int c;
    // 读取所有残留字符，直到缓冲区为空（遇到'\n'或EOF）
    while ((c = getchar()) != '\n' && c != EOF);
    char password[MAXLEN];
    getPassword(password, sizeof(password));
    /* printf("请输入密码\n"); */
    /* scanf("%s",password); */
    int len=strlen(name);
    /* while ((c = getchar()) != '\n' && c != EOF); */
    send(socketFd,&len,sizeof(int),0);
    send(socketFd,name,len,0);
    int saltLen;
    recv(socketFd,&saltLen,sizeof(int),MSG_WAITALL);
    char salt[64]={0};
    recv(socketFd,&salt,saltLen,MSG_WAITALL);
    char *pwd=NULL;
    pwd=crypt(password,salt);
    int pwdLen=strlen(pwd);
    send(socketFd,&pwdLen,sizeof(int),0);
    send(socketFd,pwd,pwdLen,0);
    /* printf("%d\n",pwdLen); */
    /* printf("%s\n",pwd); */
    int ret;
    recv(socketFd,&ret,sizeof(int),MSG_WAITALL);
    if(ret==0){
        return 0;
    }
    else{
        return -1;
    }
}

